<?php
namespace app\common\model;
use x\Xbase;
use EasyWeChat\Factory;
class Weixin extends Xbase
{
  //获取微信app对象
  public function getApp($config = []){
    if(!$config)$config = c('api.wx_gzh_config')['myb'];
    $options = [
        'app_id'    => '',
        'secret'    => '',
        'response_type' => 'array',
        'token'     => '',
        'log' => [
            'level' => 'debug',
            'file'  => '/tmp/easywechat.log',
        ],
    ];
    $options = array_merge($options,$config);
    $app = Factory::officialAccount($options);
    return $app;
  }

  #获取微信access_token   --需改curl-url
  public function getAccessToken($app_id, $secret){
    $temp = $this->db->query("select * from three_temp where uuid='wechat_access_token'");
    if ($temp) {
        if ($temp[0]['update_time']<time()) {
            $this->db->delete('three_temp',$temp[0]['id']);
        }else{
            return $temp[0]['value'];
        }
    }
    $time = time();
    $rs = Curl::get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}");
    $rs = json_decode($rs,true);
    if (!isset($rs['access_token'])) return $this->setError('获取微信access_token失败');
    $data = [
        'uuid' => 'wechat_access_token',
        'value' => $rs['access_token'],
        'create_time' => $time,
        'update_time' => $time+$rs['expires_in'],
    ];
    $result = $this->db->insert('three_temp',$data);
    return $rs['access_token'];
  }
}
